import { defaultParentID } from '@/config';
import api from '@/pages/Organization/MenuManagement/request';
import { PlusOutlined } from '@ant-design/icons';
import { DrawerForm, ProForm, ProFormText } from '@ant-design/pro-components';
import { FormattedMessage } from '@umijs/max';
import { Button, Form } from 'antd';
import { useMemo, useState } from 'react';
export type Data = MenuManagementApi.InfoResponse;
export type FormConfig = { Component: any; props: Record<string, any> };
export interface Props {
  isEdit?: boolean;
  data?: Data;
  onSuccess?: () => void;
  onCancel?: () => void;
}
const colSpan = 2;
function MenuManagementForm(props: Props) {
  const { data, isEdit = false } = props;
  const [form] = Form.useForm<Data>();
  const [info, setInfo] = useState<Partial<MenuManagementApi.InfoResponse>>({});

  const getInfo = async (params: Partial<MenuManagementApi.InfoResponse>) => {
    if (params.id) {
      const p: MenuManagementApi.InfoParams = { id: params.id };
      const data = await api.getInfo(p);
      form.setFieldsValue(data);
      setInfo(data);
    } else {
      form.setFieldsValue(params);
      setInfo(params);
    }
  };
  const onSubmit = async (form: Data) => {
    const { title, iconPath, linkName, linkPath } = form;
    const { id = '', parentID = '', orderNo = 0, isEnabled = true } = info;
    const p: MenuManagementApi.CreateParams = {
      parentID,
      orderNo,
      isEnabled,
      title,
      iconPath,
      linkName,
      linkPath,
    };
    if (isEdit) {
      const params: MenuManagementApi.UpdateParams = { id, ...p };
      const data = await api.update(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    } else {
      const data = await api.create(p);
      if (data.success) props.onSuccess?.();
      return data.success;
    }
  };
  const onOpenChange = (open: boolean) => {
    if (open) {
      const params = data ? (isEdit ? data : { parentID: data.id }) : { parentID: defaultParentID };
      getInfo(params);
    } else {
      setInfo({});
      form.resetFields();
      props.onCancel?.();
    }
  };

  const formConfig = useMemo(() => {
    const title = {
      Component: ProFormText,
      props: {
        name: 'title',
        rules: [{ required: true }],
        width: 'md',
        label: '名称',
        placeholder: '请输入名称',
      },
    };
    const iconPath = {
      Component: ProFormText,
      props: {
        name: 'iconPath',
        rules: [{ required: true }],
        width: 'md',
        label: 'Icon',
        placeholder: '请输入Icon',
      },
    };
    const linkName = {
      Component: ProFormText,
      props: {
        name: 'linkName',
        rules: [{ required: true }],
        width: 'md',
        label: '路径名称',
        placeholder: '请输入路径名称',
      },
    };
    const linkPath = {
      Component: ProFormText,
      props: {
        name: 'linkPath',
        rules: [{ required: true }],
        width: 'md',
        label: '路径',
        placeholder: '请输入路径',
      },
    };
    const createForm: {
      [key in string]: FormConfig;
    } = { title, iconPath, linkName, linkPath };
    const updateForm: {
      [key in string]: FormConfig;
    } = { title, iconPath, linkName, linkPath };
    return isEdit ? updateForm : createForm;
  }, [isEdit]);
  const drawerFormData = useMemo(() => {
    const data: FormConfig[][] = [];
    const keys = Object.keys(formConfig);
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      const index = Math.floor(i / colSpan);
      if (!data[index]) data[index] = [];
      data[index].push(formConfig[key]);
    }
    return data;
  }, [formConfig]);

  return (
    <DrawerForm
      autoFocusFirstInput
      title={`${isEdit ? '编辑' : '新建'}菜单`}
      form={form}
      drawerProps={{ destroyOnClose: true }}
      resize={{
        maxWidth: window.innerWidth * 0.8,
        minWidth: 400,
        onResize() {},
      }}
      trigger={
        isEdit ? (
          <Button type="link">编辑</Button>
        ) : !!data ? (
          <Button type="link">新建</Button>
        ) : (
          <Button type="primary">
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>
        )
      }
      onOpenChange={onOpenChange}
      onFinish={onSubmit}
    >
      {drawerFormData.map((item, i) => {
        return (
          <ProForm.Group key={i}>
            {item.map((data) => {
              const { props, Component } = data;
              return <Component key={props.name} {...props} />;
            })}
          </ProForm.Group>
        );
      })}
    </DrawerForm>
  );
}

export default MenuManagementForm;
